import { ref, reactive, computed, onMounted } from "vue";
import { ElTag, ElButton } from "element-plus";
import { getAdPlan2Statistics } from "@/api/ads";
import { message } from "@/utils/message";
import type {
  SearchFormProps,
  Plan2StatsItem,
  GroupOption,
  PlatformOption,
  Plan2StatsResponse
} from "./types";

// 获取平台文本
const getPlatformText = (platform: number | string | null | undefined): string => {
  if (!platform) return "未知平台";

  const platformNum = typeof platform === 'string' ? parseInt(platform) : platform;

  switch (platformNum) {
    case 1:
      return "TikTok";
    case 2:
      return "Facebook";
    default:
      return "未知平台";
  }
};

export function useAdPlan2Statistics() {
  const loading = ref(false);
  const dataList = ref<Plan2StatsItem[]>([]);
  const groupOptions = ref<GroupOption[]>([]);
  const platformOptions = ref<PlatformOption[]>([]);

  // 排序状态
  const sortField = ref<string>('total_cost'); // 默认按广告费用排序
  const sortOrder = ref<'asc' | 'desc'>('desc'); // 默认倒序

  // 获取最近7天的日期范围
  const getLastSevenDays = (): [string, string] => {
    const today = new Date();
    const lastWeek = new Date(today);
    lastWeek.setDate(today.getDate() - 6); // 最近7天：今天往前推6天

    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    return [formatDate(lastWeek), formatDate(today)];
  };

  // 获取当前月份的开始和结束日期
  const getCurrentMonthRange = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth(); // 0-11

    const startDate = new Date(year, month, 2);
    const endDate = new Date(year, month + 1, 1); // 下个月的第1天，即当前月的最后一天

    const formatDate = (date: Date) => {
      return date.toISOString().split('T')[0];
    };

    return {
      start: formatDate(startDate),
      end: formatDate(endDate)
    };
  };

  const currentMonthRange = getCurrentMonthRange();

  // 快速选择字段
  const quickSelect = ref('7day');

  // 搜索表单
  const form = reactive<SearchFormProps>({
    group_id: null,
    platform: null,
    date_range: getLastSevenDays() // 默认选择最近7天
  });

  // 格式化金额
  const formatAmount = (amount: number): string => {
    return new Intl.NumberFormat('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(amount);
  };

  // 排序函数
  const sortData = (data: Plan2StatsItem[]): Plan2StatsItem[] => {
    if (!sortField.value) return data;

    const sortedData = [...data].sort((a, b) => {
      const aValue = a[sortField.value as keyof Plan2StatsItem] as number;
      const bValue = b[sortField.value as keyof Plan2StatsItem] as number;

      if (sortOrder.value === 'asc') {
        return aValue - bValue;
      } else {
        return bValue - aValue;
      }
    });

    return sortedData;
  };

  // 处理排序变化
  const handleSortChange = (field: string) => {
    if (sortField.value === field) {
      // 如果点击的是当前排序字段，切换排序顺序
      sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
    } else {
      // 如果是新字段，设置为倒序
      sortField.value = field;
      sortOrder.value = 'desc';
    }

    // 重新排序当前数据
    dataList.value = sortData([...dataList.value]);
  };

  // 表格列配置
  const columns = ref([
    {
      label: "类型",
      prop: "type",
      width: 80,
      cellRenderer: ({ row }: { row: Plan2StatsItem }) => (
        <span class={`font-medium ${row.type === 'group' ? 'text-blue-600' : 'text-green-600'}`}>
          {row.type === 'group' ? '投放组' : '投放人员'}
        </span>
      )
    },
    {
      label: "名称",
      prop: "name",
      minWidth: 120,
      cellRenderer: ({ row }: { row: Plan2StatsItem }) => (
        <div>
          <div class="font-medium">{row.name}</div>
        </div>
      )
    },
    {
      label: "AD",
      prop: "total_cost",
      minWidth: 120,
      sortable: "custom",
      cellRenderer: ({ row }: { row: Plan2StatsItem }) => (
        <span class="font-mono text-red-500">
          {formatAmount(row.total_cost)}
        </span>
      )
    }
  ]);

  // 获取数据
  const fetchData = async () => {
    try {
      loading.value = true;

      // 处理日期范围
      const requestData = {
        group_id: form.group_id,
        platform: form.platform,
        // 确保date_range有默认值
        date_range: form.date_range || [currentMonthRange.start, currentMonthRange.end]
      };

      const response = await getAdPlan2Statistics(requestData);

      if (response.success) {
        const data = response.data as Plan2StatsResponse;

        // 设置数据并应用排序
        dataList.value = sortData(data.stats_data || []);

        // 只在首次加载时更新选项
        if (groupOptions.value.length === 0) {
          groupOptions.value = data.group_options || [];
        }
        if (platformOptions.value.length === 0) {
          platformOptions.value = data.platform_options || [];
        }
      } else {
        message(response.message || "获取数据失败", { type: "error" });
      }
    } catch (error) {
      console.error("获取广告计划2统计数据失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  };

  // 时间范围选择
  const selectTimeRange = (value: string) => {
    quickSelect.value = value;
    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);

    const lastWeek = new Date(today);
    lastWeek.setDate(today.getDate() - 6);

    const last30Days = new Date(today);
    last30Days.setDate(today.getDate() - 29);

    switch (value) {
      case 'today':
        form.date_range = [formatDate(today), formatDate(today)];
        break;
      case 'yesterday':
        form.date_range = [formatDate(yesterday), formatDate(yesterday)];
        break;
      case '7day':
        form.date_range = [formatDate(lastWeek), formatDate(today)];
        break;
      case '30day':
        form.date_range = [formatDate(last30Days), formatDate(today)];
        break;
      case 'month':
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 2);
        const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 1);
        form.date_range = [formatDate(monthStart), formatDate(monthEnd)];
        break;
      case 'lastmonth':
        const lastMonthStart = new Date(today.getFullYear(), today.getMonth() - 1, 2);
        const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 1);
        form.date_range = [formatDate(lastMonthStart), formatDate(lastMonthEnd)];
        break;
      case 'diy':
        // 自定义不做处理，用户手动选择
        break;
    }
  };

  const handleDateChange = () => {
    quickSelect.value = 'diy';
  };

  const onSearch = () => {
    fetchData();
  };

  const resetForm = (formEl: any) => {
    form.group_id = null;
    form.platform = null;
    form.date_range = getLastSevenDays();
    quickSelect.value = '7day';
    fetchData();
  };

  // 自定义合计方法
  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];

    // 根据展示设置决定统计哪些数据
    const userItems = data.filter(item => item.type === 'user');

    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '汇总';
        return;
      }

      if (userItems.length === 0) {
        sums[index] = '';
        return;
      }

      switch (column.property) {
        case 'type':
          sums[index] = '人员合计';
          break;
        case 'name':
          sums[index] = `共${userItems.length}人`;
          break;
        case 'total_cost':
          const totalCost = userItems.reduce((sum, item) => sum + item.total_cost, 0);
          sums[index] = `${formatAmount(totalCost)}`;
          break;
        default:
          sums[index] = '';
      }
    });

    return sums;
  };

  // 初始化
  onMounted(() => {
    fetchData();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    groupOptions,
    platformOptions,
    quickSelect,
    sortField,
    sortOrder,
    onSearch,
    resetForm,
    handleSortChange,
    selectTimeRange,
    handleDateChange,
    formatAmount,
    getSummaries
  };
}
